export function sort(array, callback) {
  if (array == null || callback == null) {
    return;
  }
  let len = array.length;
  for (var i = 0; i < len; i++) {
    let jLen = len - i;
    for (var j = 0; j < jLen; j++) {
      let a = array[j];
      let b = array[j + 1];
      if (callback(a, b) > 0) {
        let tmp = b;
        b = a;
        a = tmp;
        array[j] = a;
        array[j + 1] = b;
      }
    }
  }
}

export function defaultCompare(a, b) {
  let x = (a.sort || 0) - (b.sort || 0);
  if (x > 0) {
    return 1;
  } else if (x < 0) {
    return -1;
  } else {
    return 0;
  }
}

function _tree(parent, data, compareCallback) {
  let childs = data.filter(x => {
    return x.parentId == parent.id;
  });
  if (childs.length > 0) {
    childs.sort(compareCallback);
    childs.forEach(p => {
      _tree(p, data, compareCallback);
    })
    parent.children = childs;
  }
}

export function tree(data, compareCallback) {
  let callback = compareCallback || defaultCompare;
  let parents = data.filter(x => {
    return x.parentId == null || x.parentId == "/"
  });
  parents.sort(callback);
  parents.forEach(parent => {
    _tree(parent, data, callback);
  });
  return parents;
}

/**
 * 树形结构是否存子节点
 * 
 * @param {*} coll 
 * @param {*} node 
 */
export function hasChildren(coll, node) {
  if (node && node.id) {

  } else {
    return false;
  }
}

export function join(array, joinStr, callback) {
  let str = "";
  joinStr = joinStr || ",";
  if (array && array.length > 0) {
    str += callback ? callback(array[0]) : array[0];
    for (let i = 1; i < array.length; i++) {
      str = str + joinStr + (callback ? callback(array[i]) : array[i]);
    }
  }
  return str;
}

export default {
  utils: {
    sort, tree, join,
    "compare": defaultCompare
  }
}